<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>车型项目管理</title>
    <link rel="stylesheet" type="text/css" href="/static/layui/css/layui.css" />
    <style>
        body { font-family: Arial, sans-serif; }
        .container {
            width: 98%;
            {#margin-top: 20px;#}
            margin: 0 auto;
            {#background-color: white;#}
            {#border-radius: 12px;#}
            {#background-color: #f4f4f4;#}
        }
        .form-group { margin-bottom: 15px; }
        .form-group label { display: block; margin-bottom: 5px; }
        .form-group input, .form-group select { width: 100%; padding: 8px; box-sizing: border-box; }

        .btn { padding: 10px 15px; background-color: #007BFF; color: white; border: none; cursor: pointer; display: flex; align-items: center; justify-content: center;  }
        .btn:hover { background-color: #0056b3; }
        table { width: 100%; border-collapse: collapse; margin-top: 20px; }
        table, th, td { border: 1px solid #ddd; }
        th, td { padding: 10px; text-align: left; }
        th { background-color: #f2f2f2; }
        .header-container { display: flex; align-items: center; margin-bottom: 0; margin-top: 0; }
        .selected-row { background-color: rgba(185, 195, 251, 0.7) !important; }
        .layui-input-inline { margin-left: 10px; }
        .layui-input-inline { width: 375px !important; }
        .layui-input-inline label { margin-bottom: 5px; display: block; }
        .layui-form-select dl { max-height: 200px; }
        .layui-form-label { width: 140px !important; padding: 9px 10px !important; box-sizing: border-box; white-space: nowrap; margin-bottom: 0; }
        .project-select-container { display: flex; align-items: center; margin-left: 20px; }
        .layui-form-item { display: flex; align-items: center; margin-bottom: 0; }
    </style>
</head>
<body>
    <div class="container">
        <div class="layui-form" id="table-list">
            <table class="layui-hide" id="projectTable" lay-filter="projectTable"></table>
        </div>
    </div>

    <script type="text/html" id="toolbarDemo">
        <div class="header-container">
            <button type="button" class="layui-btn layui-btn-sm" onclick="addProject()">
                <i class="layui-icon layui-icon-add-1"></i>新增车型项目
            </button>
            <div class="project-select-container">
{#                <label class="layui-form-label">设定当前工作项目</label>#}
                <div class="layui-input-inline">
                    <select name="project" lay-verify="required" lay-search id="projectSelect" lay-filter="projectSelect">
                        <option value="">设置当前工作项目</option>
                        <!-- 这里将动态生成选项 -->
                    </select>
                </div>
            </div>
        </div>
    </script>

    <script type="text/html" id="barDemo">
        <div class="layui-clear-space">
            <a class="layui-btn layui-btn-xs" lay-event="edit">编辑</a>
            <a class="layui-btn layui-btn-xs layui-btn-danger" lay-event="delete">删除</a>
        </div>
    </script>

    <script src="/static/js/jquery-3.6.0.min.js"></script>
    <script src="../../static/admin/layui2.9.13/layui.js" type="text/javascript" charset="utf-8"></script>
    <script src="../../static/admin/js/common.js" type="text/javascript" charset="utf-8"></script>
    <script>
        layui.use(['table', 'form', 'layer'], function () {
            var table = layui.table;
            var form = layui.form;
            var layer = layui.layer;

            // 从后端获取项目选项
            $.get('/get_projects', function (data) {
                var $select = $('#projectSelect');
                data.forEach(function (item) {
                    $select.append('<option value="' + item.id + '">' + item.name + '</option>');
                });
                form.render('select'); // 重新渲染下拉框
            });

            var selectedRowId = null; // 确保 selectedRowId 在全局作用域中定义
            var selected_task_id = '{{ selected_task_id }}'; // 假设 selected_task_id 通过模板引擎传入
            var windowHeight = window.innerHeight;
            var tableHeight = windowHeight - 50; // 减去其他元素的高度和一些边距

            // 渲染表格
            table.render({
                elem: '#projectTable',
                url: '/get_tasks',
                toolbar: '#toolbarDemo',
                height: tableHeight,
                page: true,
                limit: 20,
                limits: [20, 50, 100],
                cols: [[
                    {field: 'id', title: 'ID', width: 60, sort: true, align: 'center', hide: true},
                    {type: 'numbers', title: '序号', width: 60, align: 'center'}, // 添加'序号'列
                    {field: 'name', title: '名称', width: 220, align: 'center'},
                    {field: 'abbr', title: '编码', width: 90, align: 'center'},
                    {field: 'pm', title: '负责人', width: 80, align: 'center'},
                    {field: 'state', title: '状态', width: 90, align: 'center'},
                    {field: 'ecu_info', title: '零部件', width: 80, align: 'center'},
                    {field: 'item_info', title: 'ITEM', width: 80, align: 'center'},
                    {field: 'tara_info', title: 'TARA表', width: 90, align: 'center'},
                    {field: 'risk_info', title: '风险处置', width: 110, align: 'center'},
                    {field: 'req_info', title: '安全需求', width: 90, align: 'center'},
                    {field: 'state', title: '状态', width: 90, align: 'center'},
                    {field: 'desc', title: '描述', width: 240, align: 'center'},
                    {field: 'customer', title: '企业信息', width: 220, align: 'center'},
                    {fixed: 'right', title: '操作', width: 130, minWidth: 125, align: 'center', toolbar: '#barDemo'}
                ]],
                done: function (res, curr, count) {
                    console.log('表格渲染完成');
                    // 设置特殊背景色
                    if (selected_task_id) {
                        var rows = document.querySelectorAll('.layui-table-body tr');
                        rows.forEach(function(row) {
                            var idCell = row.querySelector('td[data-field="id"]');
                            if (idCell && idCell.innerText === selected_task_id) {
                                row.classList.add('selected-row');
                            }
                        });
                    }
                }
            });

            // 表格工具栏事件
            table.on('tool(projectTable)', function (obj) {
                var data = obj.data;
                switch (obj.event) {
                    case 'edit':
                        editProject(data);
                        break;
                    case 'delete':
                        deleteProject(data.id);
                        break;
                }
            });

            // 新增项目
            window.addProject = function () {
                layer.open({
                    title: '新增任务',
                    type: 2,
                    content: '/addProjectForm',
                    area: ['620px', '460px'],
                    success: function (layero, index) {
                        console.info('table.reload()');
                        table.reload('projectTable');
                    }
                });
            };

            // 编辑项目
            window.editProject = function (project) {
                layer.open({
                    title: '编辑任务',
                    type: 2,
                    content: '/editProjectForm?id=' + project.id,
                    area: ['600px', '460px'],
                    btn: ['确认', '取消'],
                    yes: function (index, layero) {
                        var iframeWindow = window['layui-layer-iframe' + index];
                        var submitForm = iframeWindow.document.getElementById('projectForm');
                        var formData = new FormData(submitForm);
                        console.log('formData:', formData);
                        fetch('/edit_task', {
                            method: 'POST',
                            body: formData
                        })
                        .then(response => response.json())
                        .then(data => {
                            layer.msg(data.msg);
                            table.reload('projectTable');
                            layer.close(index);
                        })
                        .catch(error => {
                            console.error('Error:', error);
                            layer.msg('编辑项目失败，请重试');
                        });
                    },
                    btn2: function (index, layero) {
                        layer.close(index);
                    }
                });
            };

            // 删除项目
            window.deleteProject = function (id) {
                layer.confirm('跟此任务相关的数据将被同步删除！<br> 请再次确认要删除该项目吗？ ', {
                    btn: ['确定', '取消']
                }, function () {
                    fetch(`/delete_task/${id}`, {
                        method: 'DELETE'
                    })
                    .then(response => response.json())
                    .then(data => {
                        layer.msg(data.msg);
                        table.reload('projectTable');
                    });
                }, function () {
                    layer.msg('已取消删除');
                });
            };

            // 更新当前项目名称的函数
            function updateCurrentProjectName(projectName) {
                console.info('updateCurrentProjectName::', projectName);
                parent.updateCurrentProjectName(projectName);
            }

            // 监听表格行双击事件
            table.on('rowDouble(projectTable)', function (obj) {
                handleRowSelection(obj);
            });

            // 监听下拉框选择事件
            form.on('select(projectSelect)', function(data) {
                var selectedId = data.value;
                if (selectedId) {
                    // 模拟双击事件的处理逻辑
                    var rowData = table.cache['projectTable'].find(function (row) {
                        return row.id == selectedId;
                    });
                    if (rowData) {
                        handleRowSelection({ data: rowData });
                    }
                }
            });

            // 处理行选择的通用函数
            function handleRowSelection(obj) {
                var data = obj.data;
                var rowId = data.id;

                // 发送请求到后端处理
                console.info('selected id: ', rowId);
                fetch('/handle_select_task', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify({ id: rowId })
                })
                .then(response => response.json())
                .then(data => {
                    layer.msg(data.message);
                    // 设置行选择状态
                    var rows = document.querySelectorAll('.layui-table-body tr');
                    rows.forEach(function(row) {
                        var idCell = row.querySelector('td[data-field="id"]');
                        if (idCell && idCell.innerText == rowId) {
                            row.classList.add('selected-row');
                        } else {
                            row.classList.remove('selected-row');
                        }
                    });
                    updateCurrentProjectName(data.task_name); // 使用服务器返回的最新项目名称
                });
            }

            // 提交表单的函数
            window.submitForm = function (formElement) {
                var formData = new FormData(formElement);
                fetch('/add_task', {
                    method: 'POST',
                    body: formData
                })
                .then(response => response.json())
                .then(data => {
                    layer.msg(data.msg);
                    table.reload('projectTable');
                    layer.closeAll();
                });
            };
        });
    </script>
</body>
</html>